from django.shortcuts import render
from django.core.paginator import Paginator, InvalidPage, EmptyPage, PageNotAnInteger
from books.models import Books


# Create your views here.
def index(request):
    """获取商品信息查询对象"""
    mod = Books.objects.all()
    books_list = mod.filter()

    page_step = 7  # 分页处理，分页步长
    paginator = Paginator(books_list, 20)
    try:
        current_page = int(request.GET.get('page', 1))
        difference_page = paginator.num_pages - current_page  # 用于尾页显示检测
        if paginator.num_pages >= page_step:  # 总数大于步长下执行页数处理 
            if current_page - page_step // 2 < 1:  # 当前页小于分页步长一半时，处理前几页
                page_range = range(1, page_step + 1)
            elif current_page + page_step // 2 > paginator.num_pages:  # 处理最后几页
                page_range = range(paginator.num_pages - page_step, paginator.num_pages + 1)
            else:  # 正常情况,使当前页面始终处于正中
                page_range = range(current_page - page_step // 2, current_page + page_step // 2 + 1)
        else:  #
            page_range = paginator.page_range
        page_list = paginator.get_page(current_page)  # 使用get_page方法好处在于不用进行异常处理
    except ValueError:
        page_list = paginator.get_page(1)  # 当输入的值错误时，跳转到第一页
        page_range = range(1, page_step + 1)
        difference_page = page_step + 1  # 用于尾页显示检测
    context = {'BooksList': page_list, 'PageRange': page_range, 'PageStep': page_step,
               'DifferencePage': difference_page}  # 封装信息加载模板输出
    return render(request, "books/index.html", context)
